(function(){
	$(document).ready(function() {
		//产品型号等参数
		$('.js-attr').click(function(event) {
			var stock = parseInt($(this).attr('data-stock'))
			_goodsInfo.attr_id = parseInt($(this).attr('data-id'))
			_goodsInfo.stock = stock
			$('.js-stock').text(stock)

			$(this).siblings('.js-attr').removeClass('js-attr-selected')
			$(this).addClass('js-attr-selected')

			checkStock()
		});
		$('.js-amount').bind('input propertyChange',function(event) {
			var val = $(this).val()
			if(_goodsInfo.stock < 1){
				$(this).val(0)
			}else if(val<1){
				$(this).val(1)
			}else if(val>_goodsInfo.stock){
				$(this).val(_goodsInfo.stock)
			}
			_goodsInfo.number = $(this).val()
		});
		$('.js-amount-control').click(function(e){
			e.preventDefault()
			if(_goodsInfo.stock < 1){
				$('.js-amount').val(0)
				return false;
			}
			var val = parseInt($('.js-amount').val(),10)
			if($(this).hasClass('amount-plus')){
				if(++val>_goodsInfo.stock){
					return;
				}
			}else{
				if(--val<1){
					return;
				}
			}
			$('.js-amount').val(val)
		})

		$('.join-cart').click(function(event) {
			event.preventDefault();
			if(_userId<0){
				alert('请先登录');
				return false;
			}
			api.solo('cartAdd',[
				_goodsInfo.gopen_id,
				_goodsInfo.attr_id,
				_goodsInfo.number,
			],function(d){
				if(d.state==200){
					alert('添加成功')
					//加一个
					$('.control-cart-num').text(parseInt($('.control-cart-num').text(),10)+1)
				}else{
					alert(d.title)
				}
			})
		});

		//载入数量
		function checkStock(){
			if(_goodsInfo.stock>0){
				$('.js-amount').val(1)
			}else{
				$('.js-amount').val(0)
			}
		}
		checkStock()
		

		//图片
		$('div.goods-images div.small-img img').click(function(){
			$('.good-large-img').attr('src', $(this).attr('src'))
		})
		$('.small-img > a').click(function(){
			var value = $(this).hasClass('small-img-right')?10:-10;
			$('.small-img-box').scrollLeft(value)
		})

		//收藏
		$('.js-collect').click(function(){
			if(_userId<0){
				alert('请先登录');
				return false;
			}
			api.solo('addToCollect',[_userId,_goodsInfo.gopen_id],function(d){
				if(d.resultCode==200){
					alert('收藏成功')
				}else{
					alert('您已经收藏过了')
				}
			})
		})


		//更多信息切换器
		var choiceWapper = $('.goods-more-detail')
		var choiceBox = $('.choice-box')
		
		$('.choice-box div').click(function(e){
			e.preventDefault()
			var index = $(this).closest('.choice-box').children().index($(this))
			console.log(choiceWapper.find('.choice-box:eq('+index+')').get(0).offsetTop)
			$('html,body').animate({
				scrollTop:choiceWapper.find('.choice-box:eq('+index+')').get(0).offsetTop-110
			},500)
		})

		//评论了！
		var commentBox = $('.js-evaluation')
		var commentItem = commentBox.find('.eva-box').remove()
		var commentItemPhoto = commentItem.find('.eva-photo-item').remove()
		var commentPage = 1;
		var commentRows = 4;
		var commentTotal = 999;
		function refreshComment(callback){
			console.log('test')
			api.solo('goodsComment',[_goodsInfo.gopen_id,commentPage,commentRows],function(d){
				if(d.resultCode!=200 || d.data.total<1){
					//commentBox.empty();
					commentBox.append('<p>暂无评论</p>')
					return false;
				}
				var list = d.data.list;
				var total = d.data.total;
				commentTotal = Math.ceil(total/commentRows);
				for(var i=0,length=list.length;i<length;i++){
					var thisItem = commentItem.clone()

					thisItem.find('.eva-content-words').html(list[i]['comment'])
					thisItem.find('.put-time').html(list[i]['create_time'])
					thisItem.find('.js-buyer-name').html(list[i]['username'])
					thisItem.find('.buyer-level').html("等级："+list[i]['lv'])

					//解析图片
					if(list[i]['pic'] != null){
						for(var j in list[i]['pic']){
							var photoItem = commentItemPhoto.clone().css('background-image', 'url('+list[i]['pic'][j]['url']+')');
							thisItem.find('.eva-photo').append(photoItem)
						}
					}
					//回复
					if(list[i]['reply'] != null){
						thisItem.find('.reply-time').html(list[i]['reply_time'])
						thisItem.find('.reply-content').html(list[i]['reply'])
					}else{
						thisItem.find('.eva-reply').remove();
					}

					commentBox.append(thisItem)
				}
				commentBox.css('height', 'auto');
				callback()
			})
		}
		var pageBox = $('.turn-page')
		console.log(pageBox.find('.up'))
		var pageUpButton = pageBox.find('.up').remove()
		var pagedownButton = pageBox.find('.down').remove()
		var pageNumButton = pageBox.find('.pagenumber').remove()
		var pageMore = pageBox.find('.page-more').remove()
		//算出页码按钮
		function getPageButton(){
			////test////
			//var commentPage = 1;
			//var commentTotal = 6
			////test////
			console.log(commentPage,commentTotal)
			var stack = [];
			stack.push(pageUpButton.clone())
			stack.push(pageNumButton.clone().html(1))
			if(commentPage>3){
				stack.push(pageMore.clone())
				stack.push(pageNumButton.clone().html(commentPage-1))
				stack.push(pageNumButton.clone().html(commentPage))
				
			}else{
				for(var i=2;i<=commentPage;i++){
					stack.push(pageNumButton.clone().html(i))
				}
			}
			if(commentTotal>commentPage){
				stack.push(pageNumButton.clone().html(commentPage+1))
				if(commentTotal-commentPage==2){
					stack.push(pageNumButton.clone().html(commentTotal))
				}else if(commentTotal-commentPage>2){
					stack.push(pageMore.clone())
					stack.push(pageNumButton.clone().html(commentTotal))
				}
			}
			stack.push(pagedownButton.clone())
			console.log(stack)


			

			pageBox.empty()
			for(var i=0,length=stack.length;i<length;i++){
				console.log('page',i)
				if(stack[i].html() == (commentPage)){
					stack[i].css('color', '#000');
				}
				pageBox.append(stack[i])
			}
		}

		refreshComment(function(){
			getPageButton()
		})
		
		//评论翻页
		$('.turn-page').on('click', 'a', function(e) {
			e.preventDefault()
			var that = $(this)
			if(that.hasClass('up')){
				if(--commentPage<1) {
					commentPage++;
					console.log(commentPage)
					return;
				}
			}else if(that.hasClass('down')){
				if(++commentPage>commentTotal){
					commentPage--;
					console.log(commentPage)
					return;	
				} 
			}else if(that.hasClass('pagenumber')){
				commentPage = that.html()
			}else{
				return
			}
			console.log(commentPage)
			commentBox.height(commentBox.height())
			commentBox.empty()
			refreshComment(function(){
				getPageButton()
			})
			
		})

		//下单购买
		$('.js-buynow').click(function(){
			//检查库存
			if( $(".js-attr-selected").attr('data-stock')<1 ){
				alert("此规格暂无库存");
				return false; 
			}

			var url = $(this).attr('href');
			var attr_id = '&attr_id=' + $('.js-attr-selected').attr('data-id');
			var number = '&number=' + $('.js-amount').val();
			$(this).attr('href',url+attr_id+number)
		})



	});
})()

$(function () {
    api.solo( "goodsAllPrice", [_goodsInfo.gopen_id], function(d){
        var priceData=d.data.list;
        var pPriceData=priceData.length-1;
        var iDate=new Date(); // 获取今天时间
        iDate.setMonth(iDate.getMonth()-1);
        var categories=[];
        var data=[];
        for(var i=0; i<30; i++){
            iDate.setDate(iDate.getDate()+1);
            var priceDate=new Date(priceData[pPriceData].create_time);
            if(pPriceData-1>=0&& iDate>new Date(priceData[pPriceData-1].create_time)){
                pPriceData--;
            }
            categories[i]=iDate.getMonth()+1+"月"+ iDate.getDate()+"日";
            data[i]=parseInt(priceData[pPriceData].base_price);
        }

        $('#price-tendency').highcharts({
            title: {
                text: '商品价格变化图',
                x: -20 //center
            },
            xAxis: {
                categories: categories
            },
            yAxis: {
                title: {
                    text: '价格 (元)'
                },
                plotLines: [{
                    value: 0,
                    width: 1,
                    color: '#808080'
                }]
            },
            tooltip: {
                valueSuffix: '元'
            },
            legend: {
                layout: 'vertical',
                align: 'right',
                verticalAlign: 'middle',
                borderWidth: 0
            },
            series: [{
                name: '商品价格',
                data: data
            }]
        });
    });
});